package top.codedance.iotp.iot.sdk;

import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WsClient implements Client {
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private WsContext client;
    private boolean isDestory = true;
    public WsClient(final String uri, final WsCallbacker callbacker) {
        executorService.submit(() -> {
            try {
                client = new WsContext(uri, new WsCallbacker() {
                    @Override
                    public void onOpen(WsContextAdapter context, ServerHandshake shake) {
                        isDestory = false;
                        callbacker.onOpen(context, shake);
                    }

                    @Override
                    public void onMessage(WsContextAdapter context, String body) {
                        callbacker.onMessage(context, body);
                    }

                    @Override
                    public void onClose(WsContextAdapter context, int var1, String var2, boolean var3) {
                        isDestory = true;
                        callbacker.onClose(context, var1, var2, var3);
                    }

                    @Override
                    public void onError(WsContextAdapter context, Exception e) {
                        callbacker.onError(context, e);
                    }
                });
                client.connect();
                while (!client.getReadyState().equals(ReadyState.OPEN)) {
                    Thread.sleep(500);
                }
                while (client.isOpen() && !isDestory){
                    Thread.sleep(500);
                }
            } catch (Exception e) { }
        });
    }

    @Override
    public void send(String body){
        client.send(body);
    }

    @Override
    public void destory(){
        client.close();
    }

    @Override
    public boolean isOver(){
        return isDestory;
    }

    @Override
    public void waiting(){
        Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("WsClient over.");
            }
        }
        destory();
    }

    @Override
    public void reconnect() {
        client.reconnect();
    }
}
